package com.qymerge.manage.base.service.impl;

import com.qymerge.manage.base.dao.*;
import com.qymerge.manage.base.ro.MetaBudgetRO;
import com.qymerge.manage.base.service.IMetaBudgetService;
import com.qymerge.manage.core.bean.ActionResultRO;
import com.qymerge.manage.core.bean.DataTableRO;
import com.qymerge.manage.core.bean.PageRequest;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>Title: MetaProfitReportItemServiceImpl</p>
 * <p>Description: 利润表报表项目配置</p>
 *
 * @author Xiao
 * @date 2025/4/29 18:43
 * @version 1.0.0
 */
@Service
public class MetaBudgetServiceImpl implements IMetaBudgetService {

    @Autowired
    private IMetaBudgetDao metaBudgetDao;
    @Autowired
    private IMetaBudgetProductDao metaBudgetProductDao;
    @Autowired
    private IMetaBudgetGLDao metaBudgetGLDao;

    /**
     * 查询
     *
     * @param ro
     * @param pageRequest
     * @return
     */
    @Override
    public DataTableRO list(MetaBudgetRO ro, PageRequest pageRequest) {
        List<MetaBudgetRO> list = metaBudgetDao.list(ro, pageRequest);
        DataTableRO dataTableRO = new DataTableRO();
        int allCount = metaBudgetDao.total(ro);
        int pageSize = pageRequest.getSize();
        dataTableRO.setAll_count(allCount);
        dataTableRO.setList(list);
        dataTableRO.setCurrent_page(pageRequest.getPage());
        dataTableRO.setPage_size(pageSize);
        int allPage = (allCount % pageSize == 0 ? allCount / pageSize : allCount / pageSize + 1);
        dataTableRO.setAll_page(allPage);
        return dataTableRO;
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public MetaBudgetRO detail(Long id) {
        MetaBudgetRO metaBudgetRO = metaBudgetDao.findOne(id);
        return metaBudgetRO;
    }

    /**
     *
     * @param ro
     * @return
     */
    @Override
    public ActionResultRO save(MetaBudgetRO ro) {
        int rn = 0;
        if (ro.getId() == 0) {
            rn = metaBudgetDao.insert(ro);
        } else {
            rn = metaBudgetDao.update(ro);
        }
        return new ActionResultRO(rn, ro.getId() == 0 ? "保存成功" : "修改成功", ro.getId() == 0 ? "保存失败" : "修改失败");
    }

    @Override
    public ActionResultRO delete(Long id) {
        String msg = "";
        String errMsg = "";
        int rn = 0;

        // 删除主表数据
        rn = metaBudgetDao.remove(id);
        if (rn > 0) {
            // 删除产品
            metaBudgetProductDao.removeByBudgetId(id);
            // 删除总账类
            metaBudgetGLDao.removeByBudgetId(id);
        }

        msg = "删除成功";
        errMsg = "删除失败";
        return new ActionResultRO(true, msg, errMsg);
    }

}
